package com.aiolos.springboot.stepbystep.listener;

import com.aiolos.springboot.stepbystep.model.AyUser;
import com.aiolos.springboot.stepbystep.service.IAyUserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.List;

/**
 * 自定义监听器
 *
 * 在ServletContext上下文初始化时将用户数据缓存到Redis中
 */
@WebListener
public class AyUserListener implements ServletContextListener {

    Logger logger = LogManager.getLogger();

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private IAyUserService iAyUserService;

    //存放到Redis中的用户数据的变量名
    private static final String REDIS_ALL_USER = "ALL_USER_LIST";

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {

        //查询数据库所有用户
        List<AyUser> ayUserList = iAyUserService.findAll();
        //清除缓存中的用户数据
        redisTemplate.delete(REDIS_ALL_USER);
        //将用户数据插入到Redis中
        redisTemplate.opsForList().leftPushAll(REDIS_ALL_USER,ayUserList);
        //在真实项目中，不会在初始化时就从缓存中查询所有用户数据，需注释掉
        List<AyUser> queryUserList = redisTemplate.opsForList().range(REDIS_ALL_USER,0,-1);
        //System.out.println("Redis缓存中的用户总数:"+queryUserList.size());
        logger.info("Redis缓存中的用户总数:"+queryUserList.size());
        //System.out.println("ServletContext上下文初始化");
        logger.info("ServletContext上下文初始化");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        //System.out.println("ServletContext上下文销毁");
        logger.info("ServletContext上下文销毁");
    }
}
